/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { arePointsCoplanar, MessageTip } from '@app-cad/common/utils';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useState } from 'react';
import { ChildLineCommandProps } from './types';

type FormDataType = {
  curve: pickedLineData;
  plane: pickedFaceData;
  point: pickedVertexData;
  forward: number;
  back: number;
  angle: number;
};

type Params = {
  curve: string;
  plane: string;
  point: string;
  forward: number;
  back: number;
  angle: number;
};

export const CurveTangent = ({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) => {
  const initData: FormDataType = {
    curve: null,
    plane: null,
    point: null,
    forward: 60,
    back: 0,
    angle: 0,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);

  const { picker } = useTools();

  const execute = (preview: boolean) => {
    const { curve, plane, point, forward, back, angle } = formData;

    const params: Params = {
      curve: curve.edgeId,
      plane: plane?.meshId,
      point: point?.vertexId,
      forward,
      back,
      angle,
    };

    return confirmCommand(
      {
        type: 'Line',
        a: {
          mode: 'tangent',
          ...params,
        },
      },
      preview,
    );
  };

  const isFormDataValid = () => {
    const { curve, point, forward, back, plane, angle } = formData;

    const { edgeData = [] } = curve || {};
    const isCurveCoplanar = edgeData.length > 0 && arePointsCoplanar(edgeData);
    const isPlaneValid = isCurveCoplanar || plane != null;

    return (
      curve != null &&
      point != null &&
      isPlaneValid &&
      forward != null &&
      back != null &&
      angle != null
    );
  };

  useAsyncEffect(async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    const { forward, back } = formData;
    if (forward === 0 && back === 0) {
      clear();
      return;
    }

    await execute(true);
  }, [formData]);

  const checkAndFinishDraw = async () => {
    const { forward, back } = formData;
    if (forward === 0 && back === 0) {
      MessageTip.error('向前和向后不能同时为0');
      return;
    }

    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const {
    initEditDependency,
    initingEdit,
    confirmCommand,
    clear,
    isLoading,
    isPreviewLoading,
  } = useCommand('cmd-line-tangent', {
    commandName: 'CreateCurve',
    editDxid,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { curve, plane, point, forward, back, angle } = params;
    await initEditDependency([curve, plane, point]);
    setFormData({
      curve: picker.generatePickObjByPickID(curve) as pickedLineData,
      plane: picker.generatePickObjByPickID(plane) as pickedFaceData,
      point: picker.generatePickObjByPickID(point) as pickedVertexData,
      forward,
      back,
      angle,
    });
  }, [editDxid]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      plane: {
        type: 'string',
        format: PickInputRJSFFormat.PickPlane,
      },
      point: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      forward: {
        type: 'number',
        title: '向前偏移',
        format: NumberInputFormat.Length,
      },
      back: {
        type: 'number',
        title: '向后偏移',
        format: NumberInputFormat.Length,
      },
      angle: {
        type: 'number',
        title: '角度',
        format: NumberInputFormat.Angle,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      schema={schema}
      formData={formData}
      submitLoading={isLoading}
      previewLoading={isPreviewLoading}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:autofocus': true,
          'ui:options': {
            allowInfiniteLine: true,
          },
        },
        plane: {
          'ui:placeholder': '请输入平面（对平面曲面可选）',
        },
        point: {
          'ui:placeholder': '请输入曲线上的点',
        },
        forward: {
          'ui:placeholder': '请输入向前偏移量',
        },
        back: {
          'ui:placeholder': '请输入向后偏移量',
        },
        angle: {
          'ui:placeholder': '请输入角度',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
